<template>
	<div class="taskContainer">
		<a-menu style="background: transparent;min-width: 0;margin-bottom: 20px" v-if="pojectInfo.template == 1"  v-model:selectedKeys="menus.currentId" mode="horizontal" :items="[{label: t('control', '全部'), key: ''}, ...menus.structure]" @select="show" />
		<div class="header">
			<div style="display: flex;flex: 1;">
				<a-input v-model:value="searchData['search_AND_LIKE_title']" autocomplete="off" :placeholder="t('control', '请输入搜索内容')" style="width:250px;margin-right: 12px" />
				<a-select allowClear show-search :filter-option="filterOption" v-model:value="searchData['search_AND_EQ_weekId']" style="width:250px; margin-right: 12px"
					:placeholder="t('control', '教学周')">
					<a-select-option :value="item.id" :key="item.name" v-for="item in teachingWeekStructure">{{ item.name }}</a-select-option>
				</a-select>
			</div>
			<div>
				<a-button type="primary" @click="(pagination.current=1,tableData=[],show())">{{t('control', '查询')}}</a-button>
				<a-button style="margin-left: 10px" @click="(pagination.current=1,searchData = {},show())">{{t('control', '重置')}}</a-button>
			</div>
		</div>
		<div class="header" style="margin-top: 20px;">
			<div></div>
			<!-- <minMenu v-model="menus.currentId" :structure="menus.structure" jump="none" inline @handleMenuClick="show" /> -->
			<a-button :disabled="!selectedRowKeys.length" style="margin-left: 20px" @click="handleClick({ name: 'AI评分', record, index })">{{t('control', 'AI评分')}}</a-button>
		</div>
		<div class="content">
			<div style="flex:1;min-height: 0;overflow: auto;">
				<a-table :dataSource="tableData" :columns="columns" rowKey="id" :pagination="false"
				:scroll="{ x: 900 }"
					:row-selection="rowSelection">
					<template #bodyCell="{ column, text, record, index }">
						<template v-if="column.dataIndex === 'title'">
							<a-tooltip placement="topLeft">
								<template #title>
									<span>{{ text }}</span>
								</template>
								<span style="display: inline-block; max-width: 100%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">
									{{ text }}
								</span>
							</a-tooltip>
						</template>
						<template v-if="column.dataIndex === 'submitTime'">
							<span :style="{ color: judgeTime(record) ? 'red' : '' }">{{ text }}</span>
						</template>
						<template v-if="column.key === 'score'">
							<div>
								{{ record.score }} / {{ record.scoreSetting }}
							</div>
						</template>
						<template v-if="column.key === 'operate'">
							<a style="margin-left: 12px" @click="handleClick({ name: '查看', record, index })">{{ t('common', '查看') }}</a>
							<a style="margin-left: 12px; color: #ff454a" @click="handleClick({ name: 'ai重新评分', record, index })">{{t('common', '重新评分')}}</a>
							<!-- <a-popconfirm :title="`id为${record.id}，确定重新评分吗？`" @confirm="handleClick({ name: '重新评分', record, index })">
								<a style="margin-left: 12px; color: #ff454a">重新评分</a>
							</a-popconfirm> -->
						</template>
					</template>
				</a-table>
			</div>
			<a-pagination style="text-align: center" @change="show" v-model:current="pagination.current" show-size-changer  v-model:pageSize="pagination.size"
				:total="pagination.totalElements" />
		</div>

		<a-modal v-model:open="modal.visible" v-if="modal.visible" :maskClosable="false" :footer="null" title="AI对话评分"  width="1100px">
			<div style="height: 500px;">
				<!-- distribution-task -->
				<!-- <AIConsulting :initialData="modal.initialData" size="clear" type="/ai/dify/system/score/chatMessages" agentImg="" :record="modal.record" @handleThought="handleThought" /> -->
				<minAi :hasHeader="false" refreshRecord :initialData="modal.initialData" size="clear" url="/ai/dify/system/score/chatMessages" :record="modal.record" @handleThought="handleThought" />
			</div>
		</a-modal>

		<a-drawer
			title=""
			width="40%"
			placement="right"
			:closable="false"
			v-model:open="drawer.visible"
		>
			<div class="drawerBox">
				<div class="title">{{drawer.data.title}}</div>
				<div class="date" v-if="drawer.data.studentName">{{drawer.data.studentName}} {{t('drawer', '答复于')}} {{drawer.data.submitTime}}</div>
				<div class="reply"  v-html="renderMarkDown(drawer.data.submitContent)"></div>
				<div class="fileList">
					<!-- <a class="item" v-for="item in drawer.data.files" :href="item.url" :download="item.name"><LinkOutlined /> {{ item.name }}</a> -->
					<div class="item" v-for="item in drawer.data.files" @click="handleClick({name: '下载', record:item})"><LinkOutlined /> {{ item.name }}</div>
				</div>
				<div class="score">
					<div>{{t('drawer', "得分")}}</div>
					<div style="margin-left: 10px;">{{ drawer.data.score }}</div>
				</div>
				<div class="reason">
					<div class="subTitle">{{t('drawer', "评分原因")}}</div>
					<div class="text" v-html="renderMarkDown(drawer.data.scoreDetail)"></div>
				</div>
			</div>
		</a-drawer>
	</div>
</template>
<script setup>
import { reactive, ref, inject, computed } from 'vue'
import { teacherProjectTaskPage, teacherSchoolWeekSearch, teacherProjectTaskFindById, findTeamByProject } from '@/request/process/examine'
import { LinkOutlined } from '@ant-design/icons-vue'
import { message } from 'ant-design-vue'
import MarkdownIt from 'markdown-it'
import AIConsulting from '@/components/AIConsulting.vue'
import { state, refreshMessages } from '@/stores/info.js'
import minMenu from '@/components/common/minMenu.vue'
import minAi from '@/components/common/minAi.vue'
import { t } from '@/i18n'

let pojectInfo = JSON.parse(sessionStorage.getItem('pojectInfo') || '{}')
const searchData = reactive({ search_AND_LIKE_num: '' })
const menus = reactive({ currentId: '', structure: [], includingZeroStructure: [] })
const pagination = ref({ totalElements: 0, current: 1, size: 10 })
const formModel = ref({})
const formRef = ref()
const modal = reactive({ visible: false, formDisable: false, name: '', record: {} })
const rules = {
	name: [
		{ required: true, message: '请输入', trigger: 'change', },
	],
}
const originColumns = [
	{ title: t('table', '标题'), dataIndex: 'title', key: 'title', width: 100,ellipsis: true },
	{ title: t('table', '评分'), dataIndex: 'score', key: 'score', width: 90 },
	{ title: t('table', '负责人'), dataIndex: 'studentName', key: 'studentName', width: 90  },
	{ title: t('table', '教学周'), dataIndex: 'weekName', key: 'weekName', width: 250 },
	// { title: t('table', '小组编号'), dataIndex: 'teamId', key: 'teamId' },
	{ title: t('table', '提交时间'), dataIndex: 'submitTime', key: 'submitTime',width: 180 },
	{ title: t('table', '操作'), dataIndex: 'operate', key: 'operate', width: 150, fixed: 'right' },
]
const columns = ref([...originColumns])
const tableData = ref([])



const teachingWeekStructure = ref([])
const judgeTime = record => {
	if (!record.submitTime) return true
	let submitTime = new Date(record.submitTime).getTime()
	let expiredTime = new Date(record.expiredTime).getTime()
	if (expiredTime < submitTime) return true
	return false
}
const firstShow = async () => {
	// if (pojectInfo.template == '1') {
	// 	columns.value.splice(4,0,	{ title: '组名', dataIndex: 'teamName', key: 'teamName', width: 90 })
	// 	columns.value.splice(5,0,	{ title: '小组编号', dataIndex: 'teamId', key: 'teamId', width: 120 })
	// }
  let res = {
    教学周: await teacherSchoolWeekSearch(),
		小组编号分组: await findTeamByProject({projectId: pojectInfo.id, })
  }
	if (res['教学周']) teachingWeekStructure.value = res['教学周'].data
	if (res['小组编号分组']) {
		menus.structure = res['小组编号分组'].data.map(item => ({ ...item, label: item.teamName || `${item.leaderName || ''}${t('common', '组')}`, key: item.teamId })).filter(val => val.memberNumber)
		menus.currentId = ['']
	}
}

function clear() {
		for (let key in searchData) {
			searchData[key] = undefined
		}
		pagination.value.current=1
		show()
	}

const show = async () => {
	console.log(menus.currentId, 'menus.currentId')
	let req = {
		...pagination.value,
		page: pagination.value.current - 1,
		...searchData,
		search_AND_GE_status: 2,
		search_AND_EQ_projectId: pojectInfo.id,
		'search_AND_EQ_teamId': menus.currentId[0]
	}
	let res = await teacherProjectTaskPage(req)
	if (!res) return
	tableData.value = res.data.content
	pagination.value = {
		...pagination.value,
		...res.data.page
	}
}
(async () => {
	await firstShow()
	show()
})()

const handleThought = async val => {
	if(val.tool.includes('saveRating')) {
		// message.success('评分已成功保存')
		refreshMessages(pojectInfo)
		pagination.value.current = 1
		show()
	}
}
const renderMarkDown = text => {
	if (!text) return ''
  const md = new MarkdownIt({
    html: true,
    linkify: true,
    typographer: true,
  })
  return md.render(text)
}
const filterOption = (input, option) => {
  return option.key.indexOf(input) >= 0
}
const drawer = reactive({ visible: false, data: {} })
const selectedRowKeys = ref([])
const selectedRows = ref([])
// const onSelectChange = (keys, rows) => {
// 	selectedRowKeys.value = keys
// 	selectedRows.value = rows
// }
const rowSelection = computed(() => ({
						hideSelectAll: true,
					checkStrictly: false,
				selectedRowKeys: selectedRowKeys.value,
	onChange: (selectedKeys, rows) => {
		if (selectedKeys.length > 3) {
			selectedRowKeys.value = selectedKeys.slice(0, 3);
			selectedRows.value.splice(3, rows.length - 3);
		} else {
			selectedRowKeys.value = selectedKeys;
			selectedRows.value = rows
		}
	},
	getCheckboxProps: (record) => ({
		disabled: selectedRowKeys.value.length >= 3 && !selectedRowKeys.value.includes(record.id),
	}),
}))
const handleClick = async ({ name, record }) => {
	let req = {}, res = null
	switch (name) {
		case '下载':
			console.log(record)
			window.open(record.url)
			break
		case '查看':
			res = await teacherProjectTaskFindById({...record})
			drawer.data = res.data
			drawer.visible = true
			break
		case '重新评分':
		navigator.clipboard.writeText(record.id).then(() => {
			message.success(t('ai', 'id复制成功，正在跳转dify，请在使用前发送id给dify'))
			setTimeout(() => {
				window.open('https://dify.ai/')
			}, 2500)
    })
    .catch(err => {
			message.error(t('ai', 'id复制失败，请重试'))
    })
			break
		case 'ai重新评分':
			modal.visible = true
			modal.record = record
			modal.initialData = {
				message: `projectId:${pojectInfo.id} taskld:${record.id} userId:teacher_${state.userInfo.id} ${t('ai', '你先查询一下这个任务列表，我看看以往的评分信息。然后再重新评分,此次任务最高分是')}${record.scoreSetting}`,
				placeholder: `${t('ai', '评分说明： 。具体分数：')}`,
			}
			break
		case 'AI评分':
			// let str = ''
			// selectedRowKeys.value.map(val => str += `taskld:${val} `)
			let scoreStr = t('ai', '这些任务的最高评分分数分别是:')
			selectedRows.value.map(val => scoreStr += `${val.scoreSetting || 100} `)
			modal.visible = true
			modal.initialData = {
				message: `projectId:${pojectInfo.id} userId:teacher_${state.userInfo.id}
				${t('ai', '对任务进行评分,使用数据')}
				{"queryTaskDetails": {"userId": "teacher_${state.userInfo.id}", "taskIds": "["${selectedRowKeys.value.join('","')}"]"}}
				${scoreStr}。`,
				placeholder: ``,
			}
			break
	}
}

</script>

<style lang="scss" scoped>
$gray: #f3f3f3;
.taskContainer {
	width: 100%;
	height: 100%;
	display: flex;
	flex-direction: column;

	.header {
		display: flex;
		align-items: center;
		justify-content: space-between;
		background: white;
		border-radius: 10px;
		height: 80px;
		padding: 20px;
	}

	.content {
		margin-top: 20px;
		padding: 20px;
		overflow: auto;
		flex: 1;
		display: flex;
		flex-direction: column;
		background: white;
		border-radius: 10px;
	}
}
.drawerBox {
	height: 100%;
	display: flex;
	flex-direction: column;
	color: #333;
	font-size: 14px;
	padding: 20px;
	.title {
		font-size: 20px;
	}
	.date {
		margin-top: 15px;
	}
	.reply {
		margin-top: 15px;
		background: $gray;
		padding: 10px;
		word-wrap: break-word;
		max-height: 100%;
		overflow: auto;
	}
	.fileList {
		margin-top: 15px;
		display: flex;
		flex-direction: column;
		.item {
			cursor: pointer;
			color: #333;
			margin-bottom: 10px;
			word-break: break-all;
		}
	}
	.score {
		font-size: 20px;
		display: flex;
		margin-top: 15px;
		margin-bottom: 10px;
	}
	.reason {
		margin-top: 15px;
		display: flex;
		flex-direction: column;
		.text {
			margin-top: 15px;
		background: $gray;
		padding: 10px;
		}
	}
	

}
</style>